package com.fulihui.systemcore.repository.impl;

import com.fulihui.systemcore.dal.convertor.PropConv;
import com.fulihui.systemcore.dal.dataobj.PropertiesDO;
import com.fulihui.systemcore.dal.dataobj.PropertiesDOExample;
import com.fulihui.systemcore.dal.mapper.PropertiesDOMapper;
import com.fulihui.systemcore.dto.PropertiesDTO;
import com.fulihui.systemcore.repository.PropertiesRepository;
import com.fulihui.systemcore.request.prop.PropertiesPageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

import static org.near.toolkit.common.StringUtil.isNotBlank;

/**
 * @author Willard.Hu on 2016/3/5.
 */
@Repository
public class PropertiesRepositoryImpl implements PropertiesRepository {
    @Autowired
    private PropertiesDOMapper propertiesDOMapper;

    @Override
    public void insert(PropertiesDTO dto) {
        PropertiesDO propDO = PropConv.toDO(dto);
        propDO.setGmtCreate(new Date());
        propertiesDOMapper.insertSelective(propDO);
    }

    @Override
    public boolean updateValue(PropertiesDTO dto) {
        PropertiesDO propDO = PropConv.toDO(dto);
        return propertiesDOMapper.updateByPrimaryKeySelective(propDO) > 0;
    }

    @Override
    public boolean delete(int id) {
        return propertiesDOMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public PropertiesDTO queryByPK(int id) {
        PropertiesDO propDO = propertiesDOMapper.selectByPrimaryKey(id);
        return PropConv.toDTO(propDO);
    }

    @Override
    public List<PropertiesDTO> query(PropertiesDOExample example) {
        List<PropertiesDO> propDOs = propertiesDOMapper.selectByExample(example);
        return PropConv.toList(propDOs);
    }

    @Override
    public List<PropertiesDTO> queryPage(PropertiesPageRequest request) {
        PropertiesDOExample example = toExample(request);
        example.setOffset(request.start4Mysql());
        example.setLimit(request.getRows());
        List<PropertiesDO> propDOs = propertiesDOMapper.selectByExample(example);
        return PropConv.toList(propDOs);
    }

    @Override
    public int totalCount(PropertiesPageRequest request) {
        return (int) propertiesDOMapper.countByExample(toExample(request));
    }

    private PropertiesDOExample toExample(PropertiesPageRequest request) {
        PropertiesDOExample example = new PropertiesDOExample();
        PropertiesDOExample.Criteria criteria = example.createCriteria();
        if (isNotBlank(request.getProdName())) {
            criteria.andProdNameEqualTo(request.getProdName());
        }
        if (isNotBlank(request.getEnvType())) {
            criteria.andEnvTypeEqualTo(request.getEnvType());
        }
        return example;
    }
}
